extends Control

@export_group("UI")
@export var character_name: Label
@export var dialogue_text: Label

@export_group("对话")
@export var dialogue_content: DialogueGroup

var dialogue_index := 0
var typing_tween: Tween

func _ready() -> void:
	hide()
	
	visibility_changed.connect(func ():
		get_tree().paused = visible
	)

func display_next_dialogue():
	if dialogue_index >= len(dialogue_content.dialogue_list):
		hide()
		return
	
	var dialogue := dialogue_content.dialogue_list[dialogue_index]
	
	if typing_tween and typing_tween.is_running():
		typing_tween.kill()
		dialogue_text.text = dialogue.content
		dialogue_index += 1
	else:
		character_name.text = dialogue.character_name
		
		typing_tween = get_tree().create_tween()
		typing_tween.set_pause_mode(Tween.TWEEN_PAUSE_PROCESS)
		dialogue_text.text = ""
		for character in dialogue.content:
			typing_tween.tween_callback(append_character.bind(character)).set_delay(0.05)
		typing_tween.tween_callback(func(): dialogue_index += 1)

func append_character(character: String):
	dialogue_text.text += character

func show_dialogue(res: DialogueGroup):
	dialogue_content = res
	dialogue_index = 0
	show()
	display_next_dialogue()

func _on_gui_input(event: InputEvent) -> void:
	if event is InputEventMouseButton and event.button_index == MOUSE_BUTTON_LEFT and event.is_pressed():
		display_next_dialogue()
